package controller;

import entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2022-11-25 11:15
 * Description：<描述>
 */
@Controller
@RequestMapping("/param")
public class ParamController {

    /**
     * JavaEE组件
     */
    @RequestMapping("/test1")
    public void test1(HttpServletRequest req, HttpServletResponse res, HttpSession session) throws IOException {
        System.out.println("参数："+req.getParameter("name"));
        System.out.println("路径："+req.getServletContext().getRealPath("upload"));

        session.setAttribute("name",req.getParameter("name"));

        res.setContentType("text/html;charset=utf8");
        PrintWriter out = res.getWriter();
        out.print("<h2>成功</h2>");
        out.close();
    }

    /**
     * 向界面传递数据
     */
    @RequestMapping("/test2")
    public String test2(Model model, Map map, ModelMap modelMap){

        model.addAttribute("name","zhangsan");

        map.put("age",29);

        modelMap.addAttribute("sex","男");
        modelMap.put("hobby","game");

        return "result";
    }

    /**
     * String和基本类型
     */
    @RequestMapping("/test3/{height}")
    public String test3(@RequestParam("username") String name, @RequestParam(required = false, defaultValue = "18") int age,@PathVariable Double height){
        System.out.println(name);
        System.out.println(age);
        System.out.println(height);
        return "result";
    }


    /**
     * 自定义对象
     */
    @RequestMapping("/test4")
    public String test4(@ModelAttribute User user){

        int i  = 5 / 0;

        System.out.println(user);
        return "result";
    }


    /**
     * 在方法的上面添加@ModelAttribute
     * 作用：在调用当前Controller中所有方法之前都会先调用该方法，并将方法返回值添加到模型数据中
     */
    @ModelAttribute("types")
    public List<String> loadTypes(){
        System.out.println("ParamController.loadTypes...............");
        List<String> list = Arrays.asList("衣服","袜子","食品","数码");
        return list;
    }



}
